<template>
  <div id="app">
    <table class="tb">
      <tr>
        <th>编号</th>
        <th>品牌名称</th>
        <th>创立时间</th>
        <th>操作</th>
      </tr>
      <!-- 元素添加 -->
      <tr>
        <td><input type="number" id="num" v-model="form.id"></td>
        <td><input type="text" id="car" v-model="form.name"></td>
        <td id="time">{{timer(time)}}</td>
        <td>
          <button @click="create">添加</button>
        </td>
      </tr>
      <!-- 循环渲染的元素tr -->
      <tr v-for="(item,index) in list" :key="index">
        <td>{{item.id}}</td>
        <td>{{item.name}}</td>
        <td>{{item.time}}</td>
        <td>
          <button @click="del(index)">删除</button>
        </td>
      </tr>
      <tr v-show="!list.length">
        <td colspan="4">没有数据咯~</td>
      </tr>
    </table>
  </div>
</template>

<script>
export default {
  data () {
    return {
      list: [
        { id: 1, name: '奔驰', time: '2020-08-01' },
        { id: 2, name: '宝马', time: '2020-08-02' },
        { id: 3, name: '奥迪', time: '2020-08-03' }
      ],
      time: new Date(),
      form: {
        id: '', name: '', time: ''
      }
    }
  },
  methods: {
    del (index) {
      this.list.splice(index, 1)
    },
    timer (time) {
      return time.getFullYear() + '-' + (time.getMonth() + 1).toString().padStart(2, '0') + '-' + time.getDate().toString().padStart(2, '0')
    },
    create () {
      if (this.form.id === '' || this.form.name === '') {
        return alert('输入的数据不能为空')
      }
      if (this.list.some(item => item.id === parseInt(this.form.id))) {
        return alert('id重复！')
      }
      this.form.id = parseInt(this.form.id)
      this.form.time = this.timer(this.time)
      this.list.push(JSON.parse(JSON.stringify(this.form)))
      this.form.id = ''
      this.form.name = ''
    }
  }
}
</script>

<style>
#app {
  width: 600px;
  margin: 10px auto;
}

.tb {
  border-collapse: collapse;
  width: 100%;
}

.tb th {
  background-color: #0094ff;
  color: white;
}

.tb td,
.tb th {
  padding: 5px;
  border: 1px solid black;
  text-align: center;
}

.add {
  padding: 5px;
  border: 1px solid black;
  margin-bottom: 10px;
}
</style>
